<template>
  <div>
    <div>
      <FormPanel ref="topForm" :list="formList" :cols="3" :isSubmitBtn="false" />
    </div>
    <FilterTable
      ref="table"
      height="auto"
      :columns="tableColumns"
      columnsRef="part_partPurchase_purchasePlane_actionPanel_main"
      :dataSource="partDetailList"
      :isMemoryPagination="true"
      :onColumnsChange="tableColumns => (this.tableColumns = tableColumns)"
      :onCellChange="tableCellChange"
      :onRowSelectChange="handleTableSelectChange"
      :onSyncTableData="list => (tableSyncDataList = list)"
    >
      <template slot="moreActions">
        <span @click="handleDeleteRowData">删除</span>
      </template>
      <template slot="controls">
        <el-button size="small" type="primary" @click="batchSelectPart">批量订货</el-button>
        <el-button size="small" type="primary" @click="selectPart">添加明细</el-button>
      </template>
    </FilterTable>
    <div class="btnWrap">
      <el-button @click="closeDrawer">关 闭</el-button>
      <AjaxButton :click="handleSave" type="primary">保 存</AjaxButton>
    </div>

    <!-- 供应商选择 -->
    <BaseDialog :visible.sync="shelperVisible" title="供应商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <provideSearchHelper @close="shelperVisible = false" @onConfirm="handleDealerConfirm" />
    </BaseDialog>

    <!-- 配件选择 -->
    <BaseDialog :visible.sync="selectPartDialogVisible" title="配件选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partSelect @close="selectPartDialogVisible = false" @onConfirm="handlePartSelectConfirm" />
    </BaseDialog>
    <!-- 批量选择 -->
    <BaseDialog :visible.sync="batchSelectPartDialogVisible" title="批量订货" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <batchPartSelect @close="batchSelectPartDialogVisible = false" @onConfirm="handleDetailSelectConfirm" />
    </BaseDialog>
  </div>
</template>

<script>
import { createOrderPurchasePlan, queryBillDetailById, queryBillPartDetailById, updatePurchasePlane } from '@/api/part/partPurchase/purchasePlane';

import { formatdate, notifyAction } from '@/utils';

// import partSelect from './partSelect';
import partSelect from '@/pages/part/partPurchase/purchaseOrder/partSelect';
// import batchPartSelect from './batchPartSelect';
import batchPartSelect from '@/pages/part/partPurchase/purchaseOrder/create/batchPartSelect';
import provideSearchHelper from './provideSearchHelper';

export default {
  components: {
    partSelect,
    batchPartSelect,
    provideSearchHelper
  },
  props: {
    isAdd: Boolean,
    billId: Number
  },
  data() {
    return {
      formList: this.createFormList(),
      tableColumns: this.createTableColumns(),
      shelperVisible: false, // 是否显示供应商选择
      selectPartDialogVisible: false, // 是否显示添加明细
      batchSelectPartDialogVisible: false, // 是否显示批量添加
      partDetailList: [], // 配件列表
      tableSyncDataList: [], // 储存的table数据
      selectedTableData: [], // 选中的配件列表
      dealerInfo: {}, // 选中的经销商数据
      orderDetail: {},
      deletedPartsArr: [] // 删除的列表数据
    };
  },
  created() {
    if (!this.isAdd) {
      this.initEditData();
    }
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '单据编号',
          fieldName: 'vBillNo',
          disabled: true
        },
        // {
        //   type: 'SELECT',
        //   label: '网络',
        //   fieldName: '',
        //   itemList: [{ item: '00', value: '00' }, { item: '01', value: '01' }]
        // },
        {
          type: 'INPUT',
          label: '供应商',
          fieldName: 'customerName',
          initialValue: '',
          readonly: true,
          rules: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.handleSelectSupplier}></el-button>;
          }
        },
        {
          type: 'DATE',
          label: '计划日期',
          fieldName: 'dForecast',
          dateFormat: 'yyyy-MM-dd',
          initialValue: formatdate(new Date(), 1)
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '配件代码',
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '计划数量',
          dataIndex: 'nForecast',
          sorter: true,
          editable: true,
          defaultEditable: true,
          editType: 'number',
          min: 0,
          max: 999999,
          filter: true,
          filterType: 'number',
          precision: 2
          // editDisableRender: params => {
          //   return <el-input value={params.row.nForecast}></el-input>;
          // }
        },
        {
          title: '库存数量',
          dataIndex: 'stockQuantity',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '可用数量',
          dataIndex: 'useableQuantity',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '含税采购单价',
          dataIndex: 'planPrice',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '含税采购金额',
          dataIndex: 'total_planPrice',
          sorter: true,
          precision: 6,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '需求日期',
          dataIndex: 'dDemand',
          sorter: true,
          width: 150,
          editable: true,
          defaultEditable: true,
          editType: 'date-picker',
          dateFormat: 'yyyy-MM-dd',
          editDisableRender: params => {
            return <el-date-picker value={params.row.dDemand}></el-date-picker>;
          },
          filter: true,
          filterType: 'date-range'
        }
        // {
        //   title: '厂家配件代码',
        //   dataIndex: 'mock9'
        // }
      ];
    },
    closeDrawer() {
      this.$emit('close', false);
    },
    // 初始化编辑数据
    async initEditData() {
      let res = await queryBillDetailById({
        itemId: this.billId
      });
      this.formList.map(item => {
        item.initialValue = res.data[0][item.fieldName];
      });
      this.orderDetail = res.data[0];
      this.dealerInfo.customerCode = res.data[0].nSupplierid;

      this.$refs.table.START_LOADING();
      let partList = await queryBillPartDetailById({
        vBillNo: this.orderDetail.vBillNo
      });
      partList.data.map(item => {
        item.total_planPrice = item.planPrice * item.nForecast;
      });
      this.$refs.table.STOP_LOADING();

      this.partDetailList = partList.data;
    },
    // table行项选中变化
    handleTableSelectChange(e) {
      this.selectedTableData = e;
    },
    // 点击供应商选择搜索
    handleSelectSupplier() {
      this.shelperVisible = true;
    },
    // 供应商选择点击确定
    handleDealerConfirm(e) {
      this.dealerInfo = e;
      this.formList.find(item => item.fieldName == 'customerName').initialValue = e.customerName;
    },
    // 点击添加明细
    selectPart() {
      this.selectPartDialogVisible = true;
    },
    // 点击批量添加
    batchSelectPart() {
      this.batchSelectPartDialogVisible = true;
    },
    // 删除数据
    handleDeleteRowData() {
      if (!this.selectedTableData.length) return;
      this.deletedPartsArr = this.deletedPartsArr.concat(this.selectedTableData);
      this.$refs.table.EXECUTE_DELETE(this.selectedTableData);
    },
    // 添加明细点击确定
    handlePartSelectConfirm(e) {
      let partList = JSON.parse(JSON.stringify(e));
      // 单独添加配件计划数量字段不同需要单独处理
      partList.forEach(item => (item.nOrderQty = item.packageLiaght || 1));
      this.formatPartsData(partList);
      // this.partDetailList = this.partDetailList.concat(partList);
      this.$refs.table.EXECUTE_INSERT(partList);
      this.$notify.success({ title: '提示信息', message: '配件添加成功' });
    },
    // 往配件table列表中插入数据(批量订货)
    handleDetailSelectConfirm(e) {
      let partList = e;
      partList = JSON.parse(JSON.stringify(partList)); // 浅拷贝防止原始数据修改
      this.formatPartsData(partList);
      // this.partDetailList = this.partDetailList.concat(partList);
      this.$refs.table.EXECUTE_INSERT(partList);
      this.$notify.success({ title: '提示信息', message: '配件添加成功' });
    },
    // 循环结算传入的列表数组的含税不含税单价（新增配件初始化数据用）
    formatPartsData(list) {
      console.log(list, '初始化新增数据');
      list.map((item, index) => {
        this.$set(list[index], 'nForecast', item.nOrderQty || 1);
        this.$set(list[index], 'nPriceNoTax', item.planPrice);
        item.planPrice = item.planPrice * (1 + 0.13); // 新增配件是查询回来的都是不含税单价，单独处理
        this.$set(list[index], 'total_planPrice', item.planPrice * item.nForecast);
        this.$set(list[index], 'total_nPriceNoTax', item.nPriceNoTax * item.nForecast);
        this.$set(list[index], 'dDemand', new Date());
        this.$set(list[index], 'vVin', '');
      });
    },
    // 输入行项改变
    tableCellChange(e) {
      this.reCalculateTableData();
    },
    // 循环计算配件详情配件金额(编辑 修改时同步修改数据)
    reCalculateTableData() {
      this.tableSyncDataList.map(item => {
        item.nForecast = item.nForecast || 0;
        item.planPrice = item.planPrice || item.nPriceNoTax * (1 + 0.13); // 税率为假数据(税率暂时无接口)
        item.total_planPrice = item.planPrice * item.nForecast;
        item.total_nPriceNoTax = item.nPriceNoTax * item.nForecast;
      });
    },
    // 点击保存
    async handleSave() {
      let formData = await this.$refs.topForm.GET_FORM_DATA();
      if (!formData[1].customerName) {
        notifyAction('请选择供应商！', 'warning');
        return;
      }

      this.tableSyncDataList.map(item => {
        item.nSpaId = item.partNo;
        item.nPurPrice = item.planPrice;
        item.deleteItem = 0;
      });
      this.deletedPartsArr.map(item => {
        item.nSpaId = item.partNo;
        item.nPurPrice = item.planPrice;
        item.deleteItem = 1;
      });

      let submitData = {
        ...formData[1],
        itemId: this.billId || '',
        itemList: this.tableSyncDataList.concat(this.deletedPartsArr),
        nSupplierid: this.dealerInfo.customerCode
      };
      console.log(submitData, this.dealerInfo.customerCode);
      submitData.dForecast = submitData.dForecast.split(' ')[0];

      let res = {};
      try {
        if (this.isAdd) {
          res = await createOrderPurchasePlan(submitData);
        } else {
          res = await updatePurchasePlane(submitData);
        }
        if (res.resultCode == 200) {
          notifyAction(this.isAdd ? '添加成功' : '修改成功');
          this.closeDrawer();
          this.$emit('reSearchTableData');
        }
      } catch (err) {
        console.log(err);
      }
    }
  }
};
</script>

<style scoped>
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
